package models

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"io"
	Util "sensor/util"

	"go.mongodb.org/mongo-driver/bson"
)

type User struct {
	UserName string `bson:"userName"`
	UserId   int    `bson:"userId"`
	Password string `bson:"password"`
}

func (User) UserCollectionName() string {
	return "user"
}

func Login(username string, password string) (bool, string) {
	cursor, err := Mongo.Collection(User{}.UserCollectionName()).Find(context.Background(), bson.M{"userName": username})
	if err != nil {
		return false, "未找到对应用户"
	}
	for cursor.Next(context.Background()) {
		user := new(User)
		err = cursor.Decode(user)
		println(user.Password)
		if err != nil {
			return false, "用户解析失败"
		}
		h := md5.New()
		io.WriteString(h, password)
		sum := h.Sum(nil)
		if user.Password == hex.EncodeToString(sum[:]) {
			token, err := Util.CreateJwtToken(user.UserId, username)
			if err != nil {
				return false, "颁发Token失败"
			}
			return true, token
		} else {
			println(hex.EncodeToString(sum[:]))
			return false, "密码错误"
		}
	}
	return false, "验证失败"
}

func InsertOneUserData(sd *User) error {
	_, err := Mongo.Collection(SensorData{}.CollectionName()).InsertOne(context.Background(), sd)
	return err
}

func InsertManyUserData(sd []*User) error {
	var tmp []interface{}
	for _, t := range sd {
		tmp = append(tmp, t)
	}
	_, err := Mongo.Collection(SensorData{}.CollectionName()).InsertMany(context.Background(), tmp)
	return err
}

func GetUserData() ([]*SensorData, error) {
	data := make([]*SensorData, 0)
	cursor, err := Mongo.Collection(SensorData{}.CollectionName()).Find(context.Background(), bson.D{})
	if err != nil {
		return nil, err
	}
	for cursor.Next(context.Background()) {
		sd := new(SensorData)
		err = cursor.Decode(sd)
		if err != nil {
			return nil, err
		}
		data = append(data, sd)
	}
	return data, nil

}
